package cn.lanqiao.springboot.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    // 用于将byte数组转换为16进制的字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) { // 如果是单个数字，前面补0
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // 返回字符串的MD5加密结果
    public static String getMD5(String input) {
        try {
            // 获取MD5 Digest对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            md.update(input.getBytes());
            // 完成哈希计算，得到结果
            byte[] digest = md.digest();
            // 将字节转换为十六进制表示的字符串
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e); // 如果找不到MD5算法，抛出运行时异常
        }
    }

    public static void main(String[] args) {
        String originalString = "Hello, World!";
        String md5Result = getMD5(originalString);
        System.out.println("Original: " + originalString);
        System.out.println("MD5: " + md5Result);
    }
}
